package com.dongdongshop.service.impl.reward_points;

import com.dongdongshop.mapper.TbOrderMapper;
import com.dongdongshop.mapper.TbRewardPointsMapper;
import com.dongdongshop.pojo.order.TbOrder;
import com.dongdongshop.pojo.reward_points.TbRewardPoints;
import com.dongdongshop.service.reward_points.RewradPointsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@com.alibaba.dubbo.config.annotation.Service
public class RewardPointServiceImpl implements RewradPointsService {
    @Autowired
    private TbRewardPointsMapper tbRewardPointsMapper;
    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Override
    public void updateReward(String orderParent) {
        List<TbOrder> orderList = tbOrderMapper.selectOrderByOrderParent(orderParent);
        BigDecimal bigDecimal = new BigDecimal(0);
        for (TbOrder order : orderList) {
            BigDecimal payment = order.getPayment();
            bigDecimal = bigDecimal.add(payment);
        }
        int i = bigDecimal.intValue();
        TbRewardPoints tbRewardPoints = tbRewardPointsMapper.selectByPrimaryKey(orderList.get(0).getUserId());
        if (tbRewardPoints==null){
            TbRewardPoints newRewardPoints = new TbRewardPoints();
            newRewardPoints.setCreateTime(new Date());
            newRewardPoints.setUpdateTime(new Date());
            newRewardPoints.setUserId(orderList.get(0).getUserId());
            newRewardPoints.setRewardPoints(i*100);
            if (i*100<=10000){
                newRewardPoints.setLevel("1");
            }else if (i*100<=2000&&i*100>=10000){
                newRewardPoints.setLevel("2");
            }else if (i*100>=3000){
                newRewardPoints.setLevel("3");
            }
            tbRewardPointsMapper.insertSelective(newRewardPoints);
        }else {
            int totalReward = tbRewardPoints.getRewardPoints()+(i*100);
            tbRewardPoints.setRewardPoints(totalReward);
            if (totalReward<=10000){
                tbRewardPoints.setLevel("1");
            }else if (totalReward<=2000&&totalReward>=10000){
                tbRewardPoints.setLevel("2");
            }else if (totalReward>=3000){
                tbRewardPoints.setLevel("3");
            }
            tbRewardPointsMapper.updateByPrimaryKeySelective(tbRewardPoints);
        }
    }
}
